Page({
  data: {
    loanAmount: 100, // 贷款总额，默认为100万元
    annualInterestRate: 4.9, // 年利率，默认为4.9%
    loanTerm: 30, // 贷款年限，默认为30年
    repaymentMethod: 'equalPrincipal', // 还款方式，默认为等额本金
    result: '' // 计算结果
  },

  bindLoanAmountInput: function(e) {
    this.setData({
      loanAmount: e.detail.value
    });
  },

  bindAnnualInterestRateInput: function(e) {
    this.setData({
      annualInterestRate: e.detail.value
    });
  },

  bindLoanTermInput: function(e) {
    this.setData({
      loanTerm: e.detail.value
    });
  },

  bindRepaymentMethodChange: function(e) {
    this.setData({
      repaymentMethod: e.detail.value
    });
  },

  calculate: function() {
    const loanAmount = this.data.loanAmount * 10000; // 转换为分
    const monthlyInterestRate = this.data.annualInterestRate / 100 / 12; // 月利率
    const loanTermMonths = this.data.loanTerm * 12; // 总月数
    let monthlyPayment, totalPayment, totalInterest;

    if (this.data.repaymentMethod === 'equalPrincipal') {
      // 等额本金
      const principalPerMonth = loanAmount / loanTermMonths;
      totalInterest = 0;
      for (let i = 1; i <= loanTermMonths; i++) {
        const interest = (loanAmount - (i - 1) * principalPerMonth) * monthlyInterestRate;
        totalInterest += interest;
      }
      monthlyPayment = (principalPerMonth + totalInterest) / loanTermMonths;
    } else {
      // 等额本息
      const power = Math.pow(1 + monthlyInterestRate, loanTermMonths);
      monthlyPayment = loanAmount * monthlyInterestRate * power / (power - 1);
      totalPayment = monthlyPayment * loanTermMonths;
      totalInterest = totalPayment - loanAmount;
    }

    // 转换为万元并保留两位小数
    monthlyPayment /= 10000;
    totalInterest /= 10000;

    const resultText = `每月还款额: ${monthlyPayment.toFixed(2)} 万元\n总支付利息: ${totalInterest.toFixed(2)} 万元`;
    this.setData({
      result: resultText
    });
  }
});